
package com.platform.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.mall.entity.*;
import com.platform.modules.mall.service.*;
import com.platform.modules.sys.entity.SysSmsLogEntity;
import com.platform.modules.sys.service.SysConfigService;
import com.platform.modules.sys.service.SysSmsLogService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者: @author  <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: AppActivityController <br>
 */
@Api(tags = "AppActivityController|活动信息")
@RestController
@RequestMapping("/app/activity")
public class AppActivityController extends AppBaseController {
    @Autowired
    private MallActivityService activityService;
    @Autowired
    private MallGoodsToActivityService goodsToActivityService;
    @Autowired
    private MallGoodsService goodsService;
    @Autowired
    MallWhitelistService whitelistService;
    @Autowired
    private SysSmsLogService sysSmsLogService;
    @Autowired
    private JedisUtil jedisUtil;
    @Autowired
    SysConfigService configService;
    private String templateId;
    @Autowired
    MallUserActivityMobileService userActivityMobileService;

    /**
     * 获取活动列表
     */
    @GetMapping("list")
    @ApiOperation(value = "获取活动列表", notes = "获取活动列表")
    @ApiImplicitParams({
    })
    @IgnoreAuth
    public RestResponse list() {
        List<MallActivityEntity> activityEntities = activityService.list(new LambdaQueryWrapper<MallActivityEntity>()
                .eq(MallActivityEntity::getIsShow, 1));
        return RestResponse.success().put("data", activityEntities);
    }

    /**
     * 获取活动数据，以及商品数据
     */
    @GetMapping("getActiData/{id}")
    @ApiOperation(value = "通过ID获取活动数据", notes = "通过ID获取活动数据")
    @IgnoreAuth
    public RestResponse getActivityData(@PathVariable("id") String id) {
        return RestResponse.success().put("data", activityService.getActivityDetails(id, null));
    }



    /**
     *  获得活动相关的商品
     * @param id
     * @return
     */
    @GetMapping("getGoods/{id}")
    @ApiOperation(value = "根据活动id获得相关商品", notes = "活动信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string")
    })
    public RestResponse getGoods(@PathVariable("id") String id) {
        List<MallGoodsToActivityEntity> list = goodsToActivityService.lambdaQuery().eq(MallGoodsToActivityEntity::getActivityId, id).list();
        if (list==null||list.size()==0){
            return RestResponse.success();
        }
        List<String> goodsIds = list.stream().map(MallGoodsToActivityEntity::getGoodsId).collect(Collectors.toList());
        List<MallGoodsEntity> goods = goodsService.lambdaQuery().eq(MallGoodsEntity::getIsOnSale, Constant.IsNot.YES.getValue())
                                                                .eq(MallGoodsEntity::getIsDelete, Constant.IsNot.YES.getValue())
                                                                .in(MallGoodsEntity::getId, goodsIds)
                                                                .orderByAsc(MallGoodsEntity::getSort).list();
        return RestResponse.success().put("data", goods);
    }


    /**
     * 获取活动秒杀活动
     */
    @GetMapping("getMsAtc")
    @ApiOperation(value = "获取活动秒杀活动", notes = "获取活动秒杀活动")
    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
//            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
//                    @ExampleProperty(mediaType = "type", value = "类型"),
//            }), required = true, dataType = "string")
    })
    public RestResponse getMsAtc(@RequestParam String type,@LoginUser MallUserEntity loginUser) {
        MallActivityEntity activityEntity = activityService.getOne(new LambdaQueryWrapper<MallActivityEntity>()
                .eq(MallActivityEntity::getIsShow, 1)
                .eq(MallActivityEntity::getWhitelistType, type).last("limit 1"));
        MallUserActivityMobileEntity entity = userActivityMobileService.lambdaQuery()
                .eq(MallUserActivityMobileEntity::getActivity, activityEntity.getId())
                .eq(MallUserActivityMobileEntity::getUserId, loginUser.getId())
                .one();
        String mobile = "";
        if(org.apache.commons.lang3.ObjectUtils.anyNotNull(entity)){
            mobile = entity.getMobile();
        }
        return RestResponse.success().put("data", activityService.getActivityDetails(activityEntity.getId(), null))
                .put("activity", activityEntity)
                .put("mobile",mobile);
    }


    //    @IgnoreAuth
    @PostMapping("qualification")
    @ApiOperation(value = "绑定活动", notes = "绑定活动")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "mobile", value = "手机"),
                    @ExampleProperty(mediaType = "activityId", value = "活动id"),
                    @ExampleProperty(mediaType = "code", value = "code")
            }), required = true, dataType = "string")
    })
    public RestResponse qualification( @LoginUser MallUserEntity user) {
        JSONObject jsonParams = getJsonRequest();
        String mobile = jsonParams.getString("mobile");
        String code = jsonParams.getString("code");
        String activityId = jsonParams.getString("activityId");
        String smsCode = jedisUtil.get(Constant.PRE_SMS + mobile);

        if (StringUtils.isNullOrEmpty(smsCode)) {
            throw new BusinessException("验证码已失效，请重新获取！");
//            return RestResponse.error("验证码已失效，请重新获取");
        }
        if (!code.equals(smsCode)) {
            Integer vNumber = Integer.valueOf(jedisUtil.get(Constant.VERIFICATIONSNUMBER + mobile));
            if (null == vNumber) {
                vNumber = 0;
            }
            if (vNumber > 5) {
                jedisUtil.del(Constant.PRE_SMS + mobile);
                jedisUtil.del(Constant.VERIFICATIONSNUMBER + mobile);
            } else {
                vNumber++;
                jedisUtil.set(Constant.VERIFICATIONSNUMBER + mobile, String.valueOf(vNumber), 300);
            }
            throw new BusinessException("验证码错误");
        }
        //验证通过后删除redis中的验证码
        jedisUtil.del(Constant.PRE_SMS + mobile);
        MallUserActivityMobileEntity entity = userActivityMobileService.lambdaQuery()
                .eq(MallUserActivityMobileEntity::getActivity, activityId)
                .eq(MallUserActivityMobileEntity::getUserId, user.getId())
                .one();


        if(!org.apache.commons.lang3.ObjectUtils.anyNotNull(entity)){
            entity = new MallUserActivityMobileEntity();
            entity.setActivity(activityId);
            entity.setMobile(mobile);
            entity.setUserId(user.getId());
            userActivityMobileService.save(entity);
        }else {
            entity.setMobile(mobile);
            userActivityMobileService.updateById(entity);
        }

        return RestResponse.success("成功");
    }

    /**
     * 发送短信
     */
//    @IgnoreAuth
    @PostMapping("smsCode")
    @ApiOperation(value = "发送短信", notes = "发送短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "mobile", value = "手机"),
                    @ExampleProperty(mediaType = "activityId", value = "活动id")
            }), required = true, dataType = "string")
    })
    public RestResponse smsCode(@LoginUser MallUserEntity user) {

        JSONObject jsonParams = getJsonRequest();

        String mobile = jsonParams.getString("mobile");
        String activityId = jsonParams.getString("activityId");
        if (StringUtils.isBlank(mobile)){
            return RestResponse.error("请输入手机号码！");
        }
        if (StringUtils.isBlank(mobile) || mobile.length() != 11) {
            return RestResponse.error("手机号码格式不对！");
        }
        MallActivityEntity activity = activityService.getById(activityId);
        String isMd5= configService.getValue("WHITELIST_MD5");
        MallWhitelistEntity whitelistEntity = whitelistService.getOne(new LambdaQueryWrapper<MallWhitelistEntity>()
                .eq(MallWhitelistEntity::getValid, Constant.ONE)
                .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5)? Md5Utils.encrypt(mobile):mobile)
                .eq(MallWhitelistEntity::getType, activity.getWhitelistType())
                .last("LIMIT 1"));
        if (!org.apache.commons.lang3.ObjectUtils.anyNotNull(whitelistEntity)) {
            throw new BusinessException("非常抱歉，您暂不符合购买资格！");
        }
        MallUserActivityMobileEntity entity = userActivityMobileService.lambdaQuery()
                .eq(MallUserActivityMobileEntity::getActivity, activityId)
                .eq(MallUserActivityMobileEntity::getMobile ,mobile)
                .eq(MallUserActivityMobileEntity::getUserId, user.getId())
                .one();

        if(org.apache.commons.lang3.ObjectUtils.anyNotNull((entity))){
            throw new BusinessException("重复绑定！");
        }
//        String activityId = jsonParams.getString("activityId");
        String code = jedisUtil.get(Constant.PRE_SMS + mobile);
        // 一分钟之内不能重复发送短信
        String stint = jedisUtil.get(Constant.SMS_STINT + mobile);
        String smsCode;
        if (StringUtils.isNotBlank(stint)) {
            return RestResponse.success("短信已发送");
        } else {
            if (StringUtils.isNotBlank(code)) {
                smsCode = code;
            } else {
                //生成验证码
                smsCode = CharUtil.getRandomNum(6);
            }
        }
        //发送成功之后将验证码存入redis，有效期为5分钟
        jedisUtil.set(Constant.PRE_SMS + mobile, smsCode, 300);
        jedisUtil.set(Constant.SMS_STINT + mobile, smsCode, 60);
        jedisUtil.set(Constant.VERIFICATIONSNUMBER + mobile, "0", 300);
        SysSmsLogEntity smsLogVo = new SysSmsLogEntity();
        smsLogVo.setUserId("0");
        smsLogVo.setTemplateId(templateId);
        JSONObject js = new JSONObject();
        js.put("code", smsCode);
        smsLogVo.setCode(smsCode);
        smsLogVo.setContent(js.toString());
        smsLogVo.setMobile(mobile);
        smsLogVo.setStime(new Date());
//        sysSmsLogService.sendSms("0", smsLogVo, templateId);
        sysSmsLogService.sendSms("0", smsLogVo);
        return RestResponse.success("短信发送成功");
    }


}
